import sys
import System
import System.Threading
import clr
import time
import threading
import thread
import Queue
import napake
import nadgradnja
import SocketServer
import random

clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("Microsoft.Scripting")
clr.AddReference('System.Drawing')

from System import Action, AppDomain, UnhandledExceptionEventHandler, Windows
from System.Collections import *
clr.AddReferenceByPartialName('MySql.Data')
from MySql.Data.MySqlClient import * 
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection
from System.Threading import *
from System.Threading.Tasks import *
from System.Windows.Threading import *
from System.Text.RegularExpressions import *
clr.AddReference("SAP_dll")
from SAP_dll import *
from System.ComponentModel import BackgroundWorker
from System.Windows import Window
from napake import *
from System.Windows.Controls import *
from System.Drawing import *



IT_VERZIJA = "Lecip 010"

conStrNtpe1 = 'server=ntpe1; userid=purkat; password=purkat; database=sledljivost;'
conStrPris = 'Data Source=vmie3;initial catalog=KAKOVOST;user id=uporabnik;password=uporabnik; Connect Timeout=30'
Procesne = ArrayList()
Serijske = ArrayList()
Stanje = 0      # 0 - zagon; error- nepravilni podatki
                # 1 - definiran izdelek, caka se na rezultat
                # 2 - izdelek definiran in ima rezultat
                # 3 - izdelek vpisan v bazo


# FUNKCIJE
stevec_poizvedb = 0
class ObjectLocker(object):
      def __init__(self, obj):
              self.obj = obj
      def __enter__(self):
              global stevec_poizvedb
              stevec_poizvedb += 1
              Monitor.Enter(self.obj)
      def __exit__(self, *args):
              global stevec_poizvedb
              stevec_poizvedb -= 1
              Monitor.Exit(self.obj)

def barva_obrazca(barva):    #{Red, Blue, Green};
    obrazec.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, Action[object](obrazec.ChangeGrid), barva)

#
# POVEZAVA Z SAP
#
def poizvedbaSAP(tip, vrednost):    # Vrne array (0) Procesna, (1) Serijska
    l = ArrayList()
    ProcesnaSAP = 'n\a'
    SerijskaSAP = 'n\a'
    with ObjectLocker(SAP400):
        barva_obrazca('Blue')
        try:
            if (tip == 'P'):    # Imamo procesno
                ProcesnaSAP = vrednost
                try:
                    SerijskaSAP = SAP400().getSerial(vrednost.ToString().Substring(0,9) + 'A')
                except:
                    SerijskaSAP = SAP400().getSerial(vrednost.ToString().Substring(0,9) + 'B')
            if (tip == 'S'):    # Imamo serijsko
                SerijskaSAP = vrednost
                ProcesnaSAP = SAP400().getProcess(vrednost)
            l.Add(ProcesnaSAP)
            l.Add(SerijskaSAP)
        except Exception, e:
            debug.TraceDbg("Poizvedba na SAP neuspesna!", e.message.ToString(), "Warning")
            System.Threading.Thread.Sleep(2000)
            if (tip == 'P'):
                l.Add(vrednost)
                l.Add(e.message.ToString())
            if (tip == 'S'):
                l.Add(e.message.ToString())
                l.Add(vrednost)
        barva_obrazca('None')
        return l

#
# Poizvedba na NTPE1
#
def poizvedbaNTPE(stavek, izhod):
    dbNtpe1 = MySqlConnection(conStrNtpe1) 
    l = ArrayList()
    i=0
    print "NTPE: %s" %stavek
    with ObjectLocker(dbNtpe1):
        while dbNtpe1.State.ToString() != "Open":  
            try:
              dbNtpe1.Open()
              cmd = dbNtpe1.CreateCommand() 
              cmd.CommandText = stavek
              r = cmd.ExecuteReader () 
              l = ArrayList()
              while r.Read (): 
                  vrednost = izhod
                  for x in range(r.FieldCount):
                      vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                  l.Add(vrednost)
              r.Close () 
              barva_obrazca('None')
            except Exception, e:
              debug.TraceDbg("Povezava na NTPE1 neuspesna!", e.message.ToString(), "Warning")
              System.Threading.Thread.Sleep(2000)
              if (i<2):
                barva_obrazca('Orange')
              else:
                barva_obrazca('Red')
              i=i+1
        dbNtpe1.Close () 
        return l


#
# POVEZAVA Z PRIS
#
def poizvedbaPRIS(stavek, izhod):
    dbPris = SqlConnection(conStrPris)
    l = ArrayList()
    i = 0
    print "PRIS: %s" %stavek
    with ObjectLocker(dbPris):
        while dbPris.State.ToString() != System.Data.ConnectionState.Open.ToString():
            try:
                dbPris.Open()
                cmd = dbPris.CreateCommand() 
                cmd.CommandText = stavek
                r = cmd.ExecuteReader () 
                l = ArrayList()
                while r.Read (): 
                    vrednost = izhod
                    for x in range(r.FieldCount):
                        vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                    l.Add(vrednost)
                r.Close () 
                barva_obrazca('None')
            except Exception, e:
                debug.TraceDbg("Povezava na PRIS neuspesna!", "Stavek: %s\n%s" %(stavek, e.message.ToString()), "Warning")
                System.Threading.Thread.Sleep(1000)
                if (i<2):
                    barva_obrazca('Orange')
                else:
                    barva_obrazca('Red')
                i=i+1
        dbPris.Close () 
        return l

def bg_Poizvedba_PRIS(sender, args):
    tmp = poizvedbaPRIS(args.Argument[0], args.Argument[1])
    args.Result = tmp

def bg_Poizvedba_NTPE(sender, args):
    tmp = poizvedbaNTPE(args.Argument[0], args.Argument[1])
    args.Result = tmp

def bg_Poizvedba_SAP(sender, args):
    tmp = poizvedbaSAP(args.Argument[0], args.Argument[1])
    args.Result = tmp

def info(message = '', show=0):
    if (show):
        obrazec.image_info.Visibility = System.Windows.Visibility.Visible
        obrazec.image_info.ToolTip = '%s' %(message);
    else: 
        obrazec.image_info.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_info.ToolTip = ''

def stop(message = '', show=0):
    if (show):
        ok()
        obrazec.image_stop.Visibility = System.Windows.Visibility.Visible
        obrazec.image_stop.ToolTip = '%s' %(message);
    else: 
        obrazec.image_stop.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_stop.ToolTip = '';

def ok(message = '', show=0):
    if (show):
        stop()
        obrazec.image_ok.Visibility = System.Windows.Visibility.Visible
        obrazec.image_ok.ToolTip = '%s' %(message);
    else: 
        obrazec.image_ok.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_ok.ToolTip = '';

def warning(message = '', show=0):
    if (show):
        obrazec.image_warning.Visibility = System.Windows.Visibility.Visible
        obrazec.image_warning.ToolTip = '%s' %(message);
    else: 
        obrazec.image_warning.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_warning.ToolTip = ''

def brisiznake():
    info()
    stop()
    warning()
    ok()

# M A I N #

debug.TraceDbg("Skripta EE-offline verzije %s" %(IT_VERZIJA), "Offline nacin", "Info")

# izdelki
def bg_izdelki(sender, args):
    obrazec.label_status.Content = ''
    izdelki = args.Result
    obrazec.comboBox_izdelki.ItemsSource = izdelki

def izdelki():
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_NTPE
    worker.RunWorkerCompleted += bg_izdelki
    obrazec.comboBox_izdelki.ItemsSource = None
    obrazec.label_status.Content = 'Poizvedbe za izdelki'
    worker.RunWorkerAsync(["SELECT DISTINCT `Program` FROM `sledljivost`.`asysaba04` ORDER BY `Program`;", "{Program}"])

# operaterji
def bg_operaterji(sender, args):
    obrazec.label_status.Content = ''
    obrazec.comboBox_operaterji.ItemsSource = args.Result

def operaterji():
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_PRIS
    worker.RunWorkerCompleted += bg_operaterji
    obrazec.comboBox_operaterji.ItemsSource = None
    obrazec.label_status.Content = 'Poizvedbe za operaterji'
    worker.RunWorkerAsync(["SELECT [ID], [KONTROLOR], [IME], [DELSTEV] FROM [KAKOVOST].[dbo].[SEZKONTROLORJEV] WHERE [STATUS] = 0 ORDER BY [IME];", "{ID}\t{KONTROLOR} {IME}"])

# operacije
def bg_operacije(sender, args):
    obrazec.label_status.Content = ''
    obrazec.comboBox_operacije.ItemsSource = args.Result

def operacije():
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_PRIS
    worker.RunWorkerCompleted += bg_operacije
    obrazec.comboBox_operacije.ItemsSource = None
    obrazec.label_status.Content = 'Poizvedbe za operacijami'
    worker.RunWorkerAsync(["SELECT [ATE], [ZNAK] FROM [KAKOVOST].[dbo].[SEZATE] ORDER BY [ID];", "{ZNAK}\t{ATE}"])


# delovni nalogi
def bg_DNi_za_izdelek(sender, args):
    obrazec.label_status.Content = ''
    dn = args.Result
    obrazec.comboBox_delnalogi.ItemsSource = dn
    brisiznake()

def bg_Sprememba_cb_napake(sender, args):
    obrazec.label_status.Content = ''
    napake = args.Result
    obrazec.comboBox_pozicije_napake.ItemsSource = napake

def izdelek_changed(sender, args):
    try:
        brisiznake()
        worker1 = BackgroundWorker()
        worker1.DoWork += bg_Poizvedba_NTPE
        worker1.RunWorkerCompleted += bg_DNi_za_izdelek
        worker2 = BackgroundWorker()
        worker2.DoWork += bg_Poizvedba_PRIS
        worker2.RunWorkerCompleted += bg_Sprememba_cb_napake
        obrazec.comboBox_pozicije_napake.ItemsSource = None
        obrazec.comboBox_delnalogi.ItemsSource = None
        obrazec.label_status.Content = 'Poizvedba za del. nalogi in napakami'
        print obrazec.comboBox_izdelki.SelectedItem.ToString()
        worker2.RunWorkerAsync(["SELECT [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] FROM [KAKOVOST].[dbo].[KOSOVNICE], [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[KODA]=(SELECT [ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KODA]='%s') AND [KAKOVOST].[dbo].[SEZMATERIALOV].[ID] = [KAKOVOST].[dbo].[KOSOVNICE].[MAT];" %obrazec.comboBox_izdelki.SelectedItem.ToString(), "{POZICIJA}"])
        worker1.RunWorkerAsync(["SELECT DISTINCT `DN` FROM `sledljivost`.`asysaba04` WHERE `Program` = '%s'" %obrazec.comboBox_izdelki.SelectedItem.ToString(), "{DN}"])
    except Exception, e:
        debug.TraceDbg("Kljukec", e.message.ToString(), "Warning")

# dummy procesna stevilka
def dummyprocesna_changed(sender, args):
    if (obrazec.textBox_dummyprocesna.Text.Length != 10):
        return
    else:
        try:
            obrazec.label_status.Content = 'Poizvedba za izdelkom ter delovnim nalogom %s' %obrazec.textBox_dummyprocesna.Text
            izdelek = poizvedbaNTPE("SELECT `Program` FROM `sledljivost`.`asysaba04` WHERE `Procesna` = '%s'" %obrazec.textBox_dummyprocesna.Text, "{Program}")[0]
            delnalog = poizvedbaNTPE("SELECT `DN` FROM `sledljivost`.`asysaba04` WHERE `Procesna` = '%s'" %obrazec.textBox_dummyprocesna.Text, "{DN}")[0]
            debug.TraceDbg("Informacije za %s" %obrazec.textBox_dummyprocesna.Text, "Izdelek: %s\nDN: %s" %(izdelek, delnalog), "Info")
            obrazec.comboBox_izdelki.SelectedItem = izdelek
            obrazec.comboBox_delnalogi.SelectedItem = delnalog
            obrazec.label_status.Content = ''
            stop(0)
        except Exception, e:
            debug.TraceDbg("Procesna %s ne obstaja!" %obrazec.textBox_dummyprocesna.Text, e.message.ToString(), "Warning")
            stop("Procesna %s ne obstaja!" %obrazec.textBox_dummyprocesna.Text, 1)


def bg_Sprememba_tb_identnapake(sender, args):
    ident = args.Result
    obrazec.textBox_ident_napake.Text = ident[0]

def bg_Sprememba_tb_material(sender, args):
    material = args.Result
    obrazec.textBox_material_napake.Text = material[0]

def bg_Sprememba_cb_napakeopis(sender, args):
    napake = args.Result
    obrazec.comboBox_napake_napake.ItemsSource = napake 

def bg_Sprememba_cb_napakeopis_id(sender, args):
    napake = args.Result
    obrazec.comboBox_napake_napake.Tag = napake 

def napake_napake_changed(sender, args):
    try:
        ID = obrazec.comboBox_napake_napake.Tag
        print "ID napake %s je %s !" %(obrazec.comboBox_napake_napake.SelectedItem.ToString(), ID[obrazec.comboBox_napake_napake.SelectedIndex])
    except Exception, e:
        print e.ToString()

def pozicija_napake_changed(sender, args):
    #Pobrisemo spisek starih napak
    obrazec.textBox_ident_napake.Text = ''
    obrazec.textBox_material_napake.Text = ''
    obrazec.comboBox_napake_napake.ItemsSource = None
    obrazec.comboBox_napake_napake.Items.Clear() 
    if (obrazec.comboBox_pozicije_napake.SelectedItem == None):
        return
    #ident
    worker_ident = BackgroundWorker()
    worker_ident.DoWork += bg_Poizvedba_PRIS
    worker_ident.RunWorkerCompleted += bg_Sprememba_tb_identnapake
    worker_ident.RunWorkerAsync(["SELECT [KAKOVOST].[dbo].[KOSOVNICE].[IDENT] FROM [KAKOVOST].[dbo].[KOSOVNICE], [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[KODA]=(SELECT [ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KODA]='%s') AND [KAKOVOST].[dbo].[SEZMATERIALOV].[ID] = [KAKOVOST].[dbo].[KOSOVNICE].[MAT] AND [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s';" %(obrazec.comboBox_izdelki.SelectedItem.ToString(), obrazec.comboBox_pozicije_napake.SelectedItem.ToString()), "{IDENT}"])
    #material
    worker_mat = BackgroundWorker()
    worker_mat.DoWork += bg_Poizvedba_PRIS
    worker_mat.RunWorkerCompleted += bg_Sprememba_tb_material
    worker_mat.RunWorkerAsync(["SELECT [MATERIAL] FROM [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE ID=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[MAT] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s'));" %(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{MATERIAL}"])
    #napake
    worker_napakeopis = BackgroundWorker()
    worker_napakeopis.DoWork += bg_Poizvedba_PRIS
    worker_napakeopis.RunWorkerCompleted += bg_Sprememba_cb_napakeopis
    worker_napakeopis.RunWorkerAsync(["SELECT [NAPAK], [OPIS] FROM [KAKOVOST].[dbo].[SEZNAPAKN] WHERE [KRAJ]=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[KRAJ] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s')) ORDER BY [NAPAK]; "%(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{NAPAK}: {OPIS}"])
    worker_napakeopis_id = BackgroundWorker()
    worker_napakeopis_id.DoWork += bg_Poizvedba_PRIS
    worker_napakeopis_id.RunWorkerCompleted += bg_Sprememba_cb_napakeopis_id
    worker_napakeopis_id.RunWorkerAsync(["SELECT [OLD] FROM [KAKOVOST].[dbo].[SEZNAPAKN] WHERE [KRAJ]=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[KRAJ] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s')) ORDER BY [NAPAK]; "%(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{OLD}"])

def StartHooker(start = 0):
    if (start):
        print "Snifer vhoda je zagnan"
        debug.textBox_logging.TextChanged += hookerchangedP
        debug.textBox_logging.TextChanged += hookerchangedZ
        debug.checkBox_keyhooker.IsChecked = True
    else:
        print "Snifer vhoda je ustavljen"
        debug.textBox_logging.TextChanged -= hookerchangedP
        debug.textBox_logging.TextChanged -= hookerchangedZ 
        debug.checkBox_keyhooker.IsChecked = False

# Pridobitev spiska procesne-serijske (offline rezim)
def podatki(sender, args):
    if (obrazec.comboBox_delnalogi.SelectedItem == None):
        return
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_NTPE
    obrazec.label_status.Content = 'Poizvedbe PN'
    worker.RunWorkerCompleted += bg_SpisekProcesnih
    worker.RunWorkerAsync(["SELECT DISTINCT `ProcesnaSkupna` FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s');" %obrazec.comboBox_delnalogi.SelectedItem.ToString(), "{ProcesnaSkupna}"])

def bg_SpisekProcesnih(sender, args):
    global Procesne 
    Procesne.Clear()
    Procesne = args.Result
    obrazec.label_status.Content = ''
    worker = BackgroundWorker()
    worker.DoWork += bg_SpisekSerijskih
    obrazec.label_status.Content = 'Poizvedbe SN'
    worker.RunWorkerCompleted += bg_SpisekSerijskih_done
    worker.RunWorkerAsync([Procesne])

def bg_SpisekSerijskih(sender, args):
    global Serijske
    global Procesne
    Serijske.Clear()
    for procesna in Procesne:
        Serijske.Add(poizvedbaSAP('P', procesna)[1])
       

def bg_SpisekSerijskih_done(sender, args):
    global Serijske
    global Procesne
    obrazec.label_status.Content = ''
    print Serijske.Count
    print Procesne.Count
    if (Serijske.Count == Procesne.Count):
        for i in range(Serijske.Count):
            print "%s - %s" %(Procesne[i], Serijske[i])

# Keyhooker funkcije

def hookerchangedP(sender, args):
    serialP=Regex("P[0-9A-Z]{8}[A|B]")
    if (serialP.IsMatch(debug.textBox_logging.Text)):
        procesnast = serialP.Match(debug.textBox_logging.Text).Value
        debug.TraceDbg("Procesna se je ujela %s!" %procesnast, None, "Info")
        obdelajP(procesnast)
        debug.textBox_logging.Clear()

def hookerchangedZ(sender, args):
    serialZ=Regex("I[0-9]{11}")
    if (serialZ.IsMatch(debug.textBox_logging.Text)):
        serijskast = serialZ.Match(debug.textBox_logging.Text).Value
        debug.TraceDbg("Serijska se je ujela %s!" %serijskast, None, "Info")
        obdelajS(serijskast)
        debug.textBox_logging.Clear()

# socket funkcije
class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        podatki = self.data.ToString().Split(' ')
        if (podatki.Length == 1):
            debug.TraceDbg("%s wrote: %s" %(self.client_address[0], self.data), "SERIAL: %s" %podatki[0], "Info")
            obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](rezultat_testa), podatki[0])
        elif (podatki.Length == 2):
            debug.TraceDbg("%s wrote: %s" %(self.client_address[0], self.data), "SERIAL: %s REZULTAT: %s" %(podatki[0], podatki[1]), "Info")
            obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object, object](rezultat_testa), podatki[0], podatki[1])
        else:
            return
        
 
def rezultat_testa(serijska, res="n/a"):
    global Stanje
    if ((serijska != obrazec.label1_serijska_vobdelavi.Text.ToString()) and (res!="n/a")):
        Windows.MessageBox.Show("Serijska testiranca se ne ujema s spremnim listom!", "Rezultat testiranja", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
        return
    if (res == "n/a"):
        obdelajS(serijska)
        return
    obrazec.label1_rezultat_vobdelavi.Text = res
    Stanje = 2

def serve_on_port(port):
    HOST, PORT = "127.0.0.1", port
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()


# obdelovanje izdelka
def obdelajP(procesna):
    global Procesne
    global Stanje
    #index = Procesne.IndexOf(procesna)
    if (1):
        obrazec.label1_procesna_vobdelavi.Text = procesna
        #obrazec.label1_serijska_vobdelavi.Text = Serijske[index].ToString()
        #preveriprocesno(Procesne[index].ToString())
        Stanje = 1
    else:
        obrazec.label1_procesna_vobdelavi.Text = "ERROR"
        obrazec.label1_serijska_vobdelavi.Text = "ERROR"
        Stanje = 0

def obdelajS(serijska):
    global Procesne
    global Stanje
    #index = Serijske.IndexOf(serijska)
    if (1):
        #obrazec.label1_procesna_vobdelavi.Text = Procesne[index].ToString()
        obrazec.label1_serijska_vobdelavi.Text = serijska
        #preveriprocesno(Procesne[index].ToString())
        Stanje = 1
    else:
        obrazec.label1_procesna_vobdelavi.Text = "ERROR"
        obrazec.label1_serijska_vobdelavi.Text = "ERROR"
        Stanje = 0

def Focus():
    obrazec.label1_procesna_vobdelavi.Text = ""
    obrazec.label1_serijska_vobdelavi.Text = ""
    obrazec.label1_rezultat_vobdelavi.Text = ""
    obrazec.label1_procesna_vobdelavi.Focus()

# PASS in FAIL odlocitev, vpis NAPAKE
def click_PASS(sender, args):
    global Stanje
    try:
        if (Stanje == 2 or Stanje == 1):
            insert_stavek = ("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Text, obrazec.label1_serijska_vobdelavi.Text, obrazec.comboBox_delnalogi.SelectedItem.ToString(),
                               obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               0, obrazec.label1_rezultat_vobdelavi.Text))
            ID = poizvedbaPRIS(insert_stavek, "{}")
            if (ID != None):
                ID_izdelka = ID[0]
                ok("Izdelek vpisan kot PASS, ID vpisa %s" %ID_izdelka, 1)
                Focus()
                Stanje = 3
            else:
                stop("NI ID-ja", 1)
                Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
        else:
            if (Stanje == 0):
                stop("Vpis v bazo je ze bil izveden!", 1)
            else:
                stop("Vpis v bazo ni mozen zaradi pomanjkljivih podatkov!", 1)
    except Exception, e:
        stop("Prislo je do nenadzorovane napake. Poglej v debug okno!", 1)
        debug.TraceDbg("Prislo je do nenadzorovane napake pri vpisu v bazo", "%s" %(e.message.ToString()), "Warning")

def click_FAIL(sender, args):
    global Stanje
    try:
        if (Stanje == 2 or Stanje == 1):
            insert_stavek = ("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Text, obrazec.label1_serijska_vobdelavi.Text, obrazec.comboBox_delnalogi.SelectedItem.ToString(),
                               obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               2, obrazec.label1_rezultat_vobdelavi.Text))
            ID = poizvedbaPRIS(insert_stavek, "{}")
            if (ID != None):
                ID_izdelka = ID[0]
                ok("Izdelek vpisan kot FAIL, ID vpisa %s" %ID_izdelka, 1)
                Focus()
                Stanje  = 3
            else:
                stop("NI ID-ja", 1)
                Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
        else:
            if (Stanje == 0):
                stop("Vpis v bazo je ze bil izveden!", 1)
            else:
                stop("Vpis v bazo ni mozen zaradi pomanjkljivih podatkov!", 1)
    except Exception, e:
        stop("Prislo je do nenadzorovane napake. Poglej v debug okno!", 1)
        debug.TraceDbg("Prislo je do nenadzorovane napake pri vpisu v bazo", "%s" %(e.message.ToString()), "Warning")

def click_VPISINAPAKO(sender, args):  # vpis napake
    global Stanje
    porocilo = ""
    try:
        
        if (Stanje == 2 or Stanje == 1):
            insert_stavek = ("INSERT INTO SPREMNILISTNAPAK (PROCESNA, OPERACIJA, OPERATER, POZICIJA, NAPAKA, OPIS, ID_IZDELEK) VALUES ('%s', '%s', %s, '%s', %s, '%s', %s); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Content,  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), ID_napake, ID_izdelka, ID_izdelka))
            ID = poizvedbaPRIS(insert_stavek, "{}")
            if (ID != None):
                ID_napake = ID[0]
                porocilo += "Napaka izdelka vpisana, ID vpisa %s. " %ID_napake
            else:
                stop("NI ID-ja", 1)
                Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
            
            if (obrazec.checkBox_izloci.IsChecked == 1):
                ID = poizvedbaPRIS("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Text, obrazec.label1_serijska_vobdelavi.Text, obrazec.comboBox_delnalogi.SelectedItem.ToString(), 
                               obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               5, obrazec.label1_rezultat_vobdelavi.Text), "{}")
                porocilo += "Izdelek vpisan kot KARANTENA, ID vpisa %s" %ID_izdelka
                Stanje = 3
            ok(porocilo, 1)
        else:
            if (Stanje == 0):
                stop("Vpis v bazo je ze bil izveden!", 1)
            else:
                stop("Vpis v bazo ni mozen zaradi pomanjkljivih podatkov!", 1)
    except Exception, e:
        stop("Prislo je do nenadzorovane napake. Poglej v debug okno!", 1)
        debug.TraceDbg("Prislo je do nenadzorovane napake pri vpisu v bazo", "%s" %(e.message.ToString()), "Warning")    
    
# Preverjanje procesne izdelka - je ze bil v obdelavi, ima kaksne napaka ...
def preveriprocesno(procesna):
    try:
        izdelek_iz_procesne = poizvedbaNTPE("SELECT `Program` FROM `sledljivost`.`asysaba04` WHERE `Procesna` LIKE '%s%%'" %procesna.Substring(0,9), "{Program}")
        dn_iz_procesne = poizvedbaNTPE("SELECT `DN` FROM `sledljivost`.`asysaba04` WHERE `Procesna` LIKE '%s%%'" %procesna.Substring(0,9), "{DN}")
        napake_s = 0
        napake_w = 0
        napake_i = 0
        Opis_Napake_s = ''
        Opis_Napake_w = ''
        Opis_Napake_i = ''
        brisiznake()
        # Preverba izbranega DN (+ERROR)
        if (izdelek_iz_procesne.Count > 0 and dn_iz_procesne.Count > 0):
            if (izdelek_iz_procesne[0] != obrazec.comboBox_izdelki.Text):
                napake_s+=1
                Opis_Napake_s+='NTPE: Izdelek (%s) ne ustreza testnemu postopku (%s)\n' %(procesna, izdelek_iz_procesne[0])
            if (dn_iz_procesne[0] != obrazec.comboBox_delnalogi.Text):
                napake_s+=1
                Opis_Napake_s+='NTPE: Izdelek (%s) ni del delovnega naloga (%s)\n' %(procesna, dn_iz_procesne[0])
        else:
            napake_s+=1
            Opis_Napake_s+='NTPE: Procesna (%s) ne obstaja v sistemu!\n' %procesna

        # Ali je imela plosca napake na predhodnih operacijah (+WARNING)
        for napake in poizvedbaPRIS("SELECT ID, OPERACIJA, POZICIJA, NAPAKA FROM KAKOVOST.dbo.SPREMNILISTNAPAK WHERE PROCESNA = '%s';" %(procesna), "{ID},{OPERACIJA},{POZICIJA},{NAPAKA}"):
            napake_w+=1
            podatki = napake.Split(',')
            Opis_Napake_w+='Napaka na operaciji %s: pozicija %s, napaka %s: %s\n' %(podatki[1], podatki[2], poizvedbaPRIS("SELECT NAPAK FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{NAPAK}")[0], poizvedbaPRIS("SELECT OPIS FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{OPIS}")[0])

        # Ali je bila plosca ze prej stestirana (+INFO)
        stevilotestiranj = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s';" %(procesna.ToString().Substring(0,9),  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{}")[0])
        
        if (stevilotestiranj > 0):
            napake_i+=1
            Opis_Napake_i+='Plosca je ze bila %sx na tem testu!\n' %stevilotestiranj

        if (napake_s > 0):
            stop(Opis_Napake_s, 1)
        if (napake_w > 0):
            warning(Opis_Napake_w, 1)
        if (napake_i > 0):
            info(Opis_Napake_i, 1)

    except Exception, e:
        debug.TraceDbg("Napaka pri poizvedovanju opozorilnih znakov!", e.message.ToString(), "Warning")
        stop("Glava spremnega lista ni izpolnjena!", 1)

###########
# M A I N #
###########


izdelki()
operaterji()
operacije()
#StartHooker(0)
#obrazec.label1_procesna_vobdelavi.IsReadOnly = 0
#obrazec.label1_serijska_vobdelavi.IsReadOnly = 0
#obrazec.label1_rezultat_vobdelavi.IsReadOnly = 0
obrazec.comboBox_izdelki.SelectionChanged += izdelek_changed
obrazec.comboBox_pozicije_napake.SelectionChanged += pozicija_napake_changed
obrazec.textBox_dummyprocesna.TextChanged += dummyprocesna_changed
obrazec.comboBox_delnalogi.SelectionChanged += podatki
StartHooker(True)
t = threading.Thread(target=serve_on_port, args=[9999])
t.setDaemon(True)
t.start()
obrazec.button_green.Click += click_PASS
obrazec.button_red.Click += click_FAIL
obrazec.button_vpisi.Click += click_VPISINAPAKO
#obrazec.label1_rezultat_vobdelavi.IsReadOnly = 0